import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/entity/refund_reason_entity.dart';
import 'package:taonile/utils/singleton_manager.dart';

import '../http/api.dart';
import '../tabview/order_list.dart';

///
/// 我的订单主页
///
class OrderIndexPage extends StatefulWidget {
  int currentIndex = 0;

  OrderIndexPage({Key? key, this.currentIndex = 0}) : super(key: key);

  @override
  State<OrderIndexPage> createState() => _OrderIndexPageState();
}

class _OrderIndexPageState extends State<OrderIndexPage> {
  List<Widget> tabViews = [
    // "5": "待付款",
    // "10": "已自动取消",
    // "11": "已手动取消",
    // "15": "待发货",
    // "20": "待收货",
    // "25": "待评价",
    // "30": "已结束"
    OrderListPage(orderType: "0"),
    OrderListPage(orderType: "5"),
    OrderListPage(orderType: "15"),
    OrderListPage(orderType: "20"),
    OrderListPage(orderType: "25"),
  ];

  var tabNames = [
    '全部',
    '待付款',
    '待发货',
    '待收货',
    '待评价',
  ];

  int _currentIndex = 0;

  @override
  void initState() {
    _currentIndex = widget.currentIndex;
    cancelOrderReason();
    refundReason();

  }

  //取消订单得原因，缓存到本地
  cancelOrderReason() async {
    if (SingletonManager.instance.orderCancelReason.isNotEmpty) {
      LogUtil.v('取消原因列表已经缓存好了');
      return;
    }
    dynamic result = await Api.cancelOrderReason();
    var jsonResult = jsonDecode(jsonEncode(result));
    List<dynamic> amountObj = jsonResult['data'];
    List<String> reason = [];
    for (var item in amountObj) {
      reason.add(item.toString());
    }
    SingletonManager.instance.orderCancelReason = reason;
  }

  //退款的得原因，缓存到本地
  refundReason() async {
    if (SingletonManager.instance.refundReason.isNotEmpty) {
      LogUtil.v('退款原因列表已经缓存好了');
      return;
    }
    dynamic result = await Api.drawbackList('0');
    var jsonResult = jsonDecode(jsonEncode(result));
    RefundReasonEntity entity = RefundReasonEntity.fromJson(jsonResult);
    SingletonManager.instance.refundReason = entity.data;
  }



  //返回菜单item
  getMenuItem(int position) {
    return InkWell(
      onTap: () {
        setState(() {
          _currentIndex = position;
        });
      },
      child: Container(
        width: 150.w,
        decoration: BoxDecoration(color: Colors.transparent),
        padding: EdgeInsets.fromLTRB(0.w, 0, 0.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _currentIndex == position
                ? Text(
                    tabNames[position],
                    style: TextStyle(color: (Config.colorMain), fontSize: 25.sp),
                  )
                : Text(
                    tabNames[position],
                    style: TextStyle(color: (Config.colorText1), fontSize: 25.sp),
                  ),
            Opacity(
              opacity: _currentIndex == position ? 1 : 0,
              child: Container(
                width: 50.w,
                margin: EdgeInsets.only(top: 6.w),
                child: Divider(
                  color: Config.colorMain,
                  height: 3.w,
                  thickness: 3.w,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('我的订单'),
        centerTitle: true,
        elevation: 0,
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          children: [
            Container(
              decoration: BoxDecoration(color: Config.colorWhite),
              width: double.infinity,
              height: 65.w,
              child: ListView.builder(
                itemCount: tabNames.length,
                padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 0),
                shrinkWrap: true,
                scrollDirection: Axis.horizontal,
                physics: const BouncingScrollPhysics(),
                itemBuilder: (BuildContext context, int index) {
                  return getMenuItem(index);
                },
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 63.w),
              child: IndexedStack(
                index: _currentIndex,
                children: tabViews,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
